package com.arpa.ntocc.common.security.filter;

import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.util.LogUtil;
import com.arpa.ntocc.common.service.authorize.AuthorizeTokenService;
import org.apache.logging.log4j.LogManager;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.shiro.web.servlet.AdviceFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出登录过滤器
 * @author leo
 */
public class OauthLogoutFilter extends AdviceFilter {

    static org.apache.logging.log4j.Logger logger = LogManager.getLogger(OauthLogoutFilter.class);


    private AuthorizeTokenService authorizeTokenService;

    /**
     * 在拦截器链执行之前执行；如果返回true则继续拦截器链；否则中断后续的拦截器链的执行直接返回；进行预处理（如基于表单的身份验证、授权）
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest req, ServletResponse resp) throws IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers","*");
        OAuthAccessResourceRequest oauthRequest;
        String accessToken;
        //客户端应用安全码
        String device_id = request.getHeader("device_id");
        try {
            //构建OAuth资源请求
            oauthRequest = new OAuthAccessResourceRequest(request);
            //获取Access Token
            accessToken = oauthRequest.getAccessToken();
            authorizeTokenService.deleteByToken(accessToken);
        } catch (OAuthProblemException e) {
            logger.error(LogUtil.log("退出失败:"+e.getMessage()));
            response.getWriter().write(Result.error(e.getDescription()).toString());
            return false;
        } catch (OAuthSystemException e) {
            logger.error(LogUtil.log("退出失败:"+e.getMessage()));
            response.getWriter().write(Result.error(e.getMessage()).toString());
            return false;
        }
        return true;
    }

    public void setAuthorizeTokenService(AuthorizeTokenService authorizeTokenService) {
        this.authorizeTokenService = authorizeTokenService;
    }

}
